# Create your views here.
#coding=utf-8
import datetime
import random

from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger
from datetime import date
from django.core.urlresolvers import reverse
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson
from django.http import Http404
from goplay.activity import forms
from models import Activity,Suggestion,JoinActivity
from goplay.sinaweibo.models import UserInfo
from goplay.sinaweibo.models import Province
from goplay.sinaweibo.views import updateWeibo
from goplay.shop import views
from goplay.activity import userRelation
'''import logging
LOG_FILENAME = 'example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)'''

TODAY=date.today()

def check_login(func):
    def new_func(request,id):
        if 'userinfo' in request.session:
            return func(request,id)    
        else:
            return HttpResponseRedirect(reverse('login'))               
    return new_func

def one_check_login(func):
    def new_func(request):
        if 'userinfo' in request.session:
            return func(request)    
        else:
            return HttpResponseRedirect(reverse('login'))               
    return new_func

def AddActivity(request):
    if request.method=="POST":
        form=forms.AddActivityForm(request.POST.copy())
        date=''
        activity=''
        address=''
        if form.is_valid():
            sinauser=request.session['userinfo']
            username=sinauser['username']
            ''''i=int(form.cleaned_data['date'])
            j=int(form.cleaned_data['activity'])
            date=form.fields['date'].choices[i-1][1]
            activity=form.fields['activity'].choices[j-1][1]'''
            date=form.cleaned_data['date']          
            activity=form.cleaned_data['activity']
            address=form.cleaned_data['address']
            weibo=form.cleaned_data['weibo']
            gongkai=form.cleaned_data['gongkai']
            acti=Activity(username=username,province=sinauser['province'],city=sinauser['city'],activityname=activity,address=address,member=username,is_open=gongkai,date=date,datetime=datetime.datetime.now())
            acti.save()
            if weibo=='True' and request.session.get('oauth_access_token')!=None:
                updateWeibo(request,date,activity)
            else:
                pass
        else:
            return HttpResponseRedirect(reverse('index'))
    #return render_to_response("activity.html",,context_instance=RequestContext(request))
    #return render_to_response("activity/activity.html",{'date':date,'activity':activity},context_instance=RequestContext(request))
    return HttpResponseRedirect(reverse('index'))

def activityMember(request,activityId,interest):
    try:
        activityId=int(activityId)
        sinauser=request.session['userinfo']
        activityInfo=Activity.objects.filter(id=activityId).values('member')
        members=activityInfo[0].get('member')
        if(interest=='do'):
            #logging.debug('hello')
            if sinauser['username'] not in members:
                member_name=members+","+sinauser['username']
                Activity.objects.filter(id=activityId).update(member=member_name) 
                '''存储我加入的活动到joinactivity表中'''   
                JoinActivity.ja_objects.create_joinActivity(sinauser['username'],activityId)
        elif(interest=='do_cancel'):
            members_list=members.split(',')
            members_list.remove(sinauser['username'])
            member_name=",".join(members_list)
            Activity.objects.filter(id=activityId).update(member=member_name) 
            '''从joinactivity表中删除我加入的活动'''   
            j=JoinActivity.objects.get(username=sinauser['username'],activityId=activityId)
            j.delete()
    except ValueError:
    #except Exception,data:
        #logging.debug(data)
        #logging.debug('except')
        raise Http404()
    return HttpResponseRedirect(reverse('activityInfo',args=[activityId]))



def delActivity(request):
    if request.method=='GET':
        GET=request.GET
        activityId=GET.get('a_id')
        a=Activity.objects.get(id=activityId)
        a.delete()
        results={'success':True}
        json = simplejson.dumps(results)
        return HttpResponse(json, mimetype='application/json')
    else:
        raise Http404()

'''活动的详细信息：活动的创建时间、地点；活动的参与者；别人给出的活动建议'''
@check_login
def activityInfo(request,activityId):
    sinauser=request.session['userinfo']
    username=sinauser['username']
    activity_member=[]
    memberInfo={}
    activityInfo=Activity.objects.filter(id=activityId).values('id','username','province','city','activityname','member','address','date','datetime')
    
    shops=views.match_shop(activityInfo[0].get('activityname'))
    suggestions=suggestionInfo(request,activityId)
    
    #city_Name=Province.objects.filter(province_id=activityInfo[0].get('province'),city_id=activityInfo[0].get('city'))
    activity=activityInfo[0]
    #activity['cityname']=city_Name[0]
    member_name=activityInfo[0].get('member')
    member_name_list=member_name.split(',')
    if username in member_name_list:
        joined=True
    else:
        joined=False
    for member_name in member_name_list:
        member_image=UserInfo.objects.filter(username=member_name).values('id','profile_image')
        memberInfo['name']=member_name
        memberInfo['member_id']=member_image[0].get('id')
        memberInfo['profile_image']=member_image[0].get('profile_image')
        activity_member.append(dict(memberInfo))
    return render_to_response("activity/activityInfo.html",{'activityInfo':activity,'members':activity_member,'suggestions':suggestions[0],'pages':suggestions[1],'page_range':suggestions[2],'shops':shops,'suggestionform':forms.addSuggestionForm(),'joined':joined},context_instance=RequestContext(request))


def suggestionInfo(request,activityId):
    after_range_num=10
    bevor_range_num=9
    try:
        page=int(request.GET.get("page",1))
        if page<1:
            page=1
    except ValueError:
        page=1
        
    a=Activity.objects.get(id=activityId)
    info=a.suggestion_set.all().order_by('-datetime').values('id','author_id','suggestion_author','suggestContext','datetime')
    paginator=Paginator(info,10)
    
    try:
        suggestions=paginator.page(page)
    except(EmptyPage,InvalidPage,PageNotAnInteger):
        suggestions=paginator.page(1)
    
    if page>=after_range_num:
        page_range=paginator.page_range[page-after_range_num+bevor_range_num]
    else:
        page_range=paginator.page_range[0:int(page)+bevor_range_num]
    
    return info,suggestions,page_range

def addSuggestion(request):
    if request.method=='POST':
        form=forms.addSuggestionForm(request.POST.copy())
        if form.is_valid():
            userinfo=request.session['userinfo']
            suggestion=form.cleaned_data['suggestion']
            activityId=form.cleaned_data['activityId']
            s=Suggestion(activity_id=activityId,author_id=userinfo['id'],suggestion_author=userinfo['username'],suggestContext=suggestion,datetime=datetime.datetime.now())
            s.save()
        else:
            return HttpResponseRedirect(reverse('index')) 
        return HttpResponseRedirect(reverse('index'))
    

    elif request.method=='GET':
        GET = request.GET
        if GET.has_key(u'a_id') and GET.has_key(u'a_sugg'):
            userinfo=request.session['userinfo']
            activityId = GET[u'a_id']
            suggestion = GET[u'a_sugg']
            s=Suggestion(activity_id=activityId,author_id=userinfo['id'],suggestion_author=userinfo['username'],suggestContext=suggestion,datetime=datetime.datetime.now())
            s.save()
            results={'success':True}
        json = simplejson.dumps(results)
        return HttpResponse(json, mimetype='application/json')
     
    #return HttpResponseRedirect(reverse('index'))

def delSuggestion(request):
    if request.method=="GET":
        GET=request.GET
        if GET.has_key('s_id'):
            s_id=GET[u's_id']
            s=Suggestion.objects.get(id=s_id)
            s.delete()
            result={'success':True}
        json=simplejson.dumps(result)
        return HttpResponse(json,mimetype='application/json')
    

#随机寻找别的用户的活动，感兴趣的话可以加入
@one_check_login
def suiyu(request):      
    suiyu=[]
    userinfo=request.session['userinfo']
    if request.method=="GET":
        GET=request.GET
        if GET.has_key('i'):
            results={'success':True}
            json = simplejson.dumps(results)
            return HttpResponse(json, mimetype='application/json')
        elif GET.has_key('s'):
            id=Activity.objects.filter(username=userinfo['username']).values('id').order_by('-datetime')[0]
            Activity.objects.filter(id=id.get('id')).update(is_open="True")
            count=Activity.objects.filter().count()
            j=random.randint(0,count-1)
            i=random.randint(0,j)   
            activityInfo=Activity.objects.filter().order_by('-datetime').values('id','username','activityname','date','province','city','address')[i]
            if activityInfo:
                cityName=Province.objects.filter(province_id=activityInfo.get('province'),city_id=activityInfo.get('city'))
                acti=activityInfo
                acti['city']=cityName[0]
                userinfo=UserInfo.objects.filter(username=activityInfo.get('username')).values('profile_image','gender')
                suiyu.append(dict(acti,**userinfo[0]))
            else:
                suiyu=[]
            return render_to_response('activity/suiyu.html',{'suiyu':suiyu,"count":count},context_instance=RequestContext(request))
            
        else:         
            isopen=Activity.objects.filter(username=userinfo['username']).values('is_open').order_by('-datetime')[0]
            if isopen.get('is_open')=='True':
                #count=Activity.objects.filter(date__gte=TODAY).count()
                count=Activity.objects.filter().count()
                j=random.randint(0,count-1)
                i=random.randint(0,j)   
                activityInfo=Activity.objects.filter().order_by('-datetime').values('id','username','activityname','date','province','city','address')[i]
                if activityInfo:
                    cityName=Province.objects.filter(province_id=activityInfo.get('province'),city_id=activityInfo.get('city'))
                    acti=activityInfo
                    acti['city']=cityName[0]
                    userinfo=UserInfo.objects.filter(username=activityInfo.get('username')).values('profile_image','gender')
                    suiyu.append(dict(acti,**userinfo[0]))
                else:
                    suiyu=[]
                return render_to_response('activity/suiyu.html',{'suiyu':suiyu,"count":count},context_instance=RequestContext(request))
            else:
                return render_to_response('activity/pre_suiyu.html',{},context_instance=RequestContext(request))
    else:
        return HttpResponse(reverse('index'))

    
#用户发起以及参加的所有的活动
@check_login
def people(request,userId):
    userinfo=request.session['userinfo']
    ifadd=userRelation.if_friend(str(userinfo['id']), str(userId))
    activity=[]
    after_range_num=10
    bevor_range_num=9
    try:
        page=int(request.GET.get("page",1))
        if page<1:
            page=1
    except ValueError:
        page=1  
                  
    isme=False
    
    if(long(userId)==userinfo['id']):
        isme=True    
                   
    if request.GET.get("tag")=='2':
        tag='2'
        user=UserInfo.objects.filter(id=userId).values('id','username','profile_image')
        username=user[0].get('username')
        joinedActivityIds=JoinActivity.objects.filter(username=username).values('activityId')
        if joinedActivityIds:
            for joinedActivityId in joinedActivityIds:
                ja=Activity.objects.filter(id=joinedActivityId.get('activityId')).values('id','username','activityname','date','datetime')         
                if ja:
                    userinfo=UserInfo.objects.filter(username=ja[0].get('username')).values('id','profile_image')
                    ja[0]['issuer_id']=userinfo[0].get('id')
                    ja[0]['issuer_image']=userinfo[0].get('profile_image')
                    activity.append(ja[0])
                    paginator=Paginator(activity,10)
                else:
                    pass
        else:
            paginator=''
    else:
        tag='1'
        user=UserInfo.objects.filter(id=userId).values('id','username','profile_image')
        username=user[0].get('username')
        activity=Activity.objects.filter(username=username).order_by('-datetime').values('id','activityname','date','member','datetime')
        if activity:
            paginator=Paginator(activity,10)
        else:
            paginator=''   
    if paginator:   
        try:
            pages=paginator.page(page)
        except(EmptyPage,InvalidPage,PageNotAnInteger):
            pages=paginator.page(1)
        if page>=after_range_num:
            page_range=paginator.page_range[page-after_range_num+bevor_range_num]
        else:
            page_range=paginator.page_range[0:int(page)+bevor_range_num]
    else:
        pages=''
        page_range=''
                
    return render_to_response('activity/people.html',{'tag':tag,'user':user[0],'pages':pages,'page_range':page_range,'issuedActivity':activity,'isme':isme,'username':username,'ifadd':ifadd,'form':forms.addFriendForm(),'userid':userId},context_instance=RequestContext(request))

'''@check_login
def people_name(request,username):
    isme=False
    username=username.encode('utf-8')
    userinfo=request.session['userinfo']
    if(username==userinfo['username']):
        isme=True
    user=UserInfo.objects.filter(username=username)
    if user:
        joinedActivity=[]
        issuedActivity=Activity.objects.filter(username=username).order_by('-datetime').values('id','activityname','date','member','datetime')
        joinedActivityIds=JoinActivity.objects.filter(username=username).values('activityId')
        for joinedActivityId in joinedActivityIds:
            ja=Activity.objects.filter(id=joinedActivityId.get('activityId')).values('username','activityname','date','member')
            if ja:
                joinedActivity.append(ja[0])
            else:
                pass
        return render_to_response('activity/people.html',{'issuedActivity':issuedActivity,"joinedActivity":joinedActivity,'isme':isme,'username':username},context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('index'))'''



@one_check_login
def tags(request):
    count=Activity.objects.filter().count()
    if count>50:
        activity=Activity.objects.filter().distinct().values('activityname')[0:50]
    else:
        activity=Activity.objects.filter().distinct().values('activityname')
    if activity:
        tags=activity
        return render_to_response('activity/tags.html',{'tags':tags},context_instance=RequestContext(request))
    else:
        return render_to_response('activity/tags.html',{'tags':'null'},context_instance=RequestContext(request))
        